<template>
    <a-page-header
        style="border: 1px solid rgb(235, 237, 240)"
        title="直播课程"
        :sub-title="$route.query.content"
        @back="()=> {
          if(living) {
            backHandler();
          } else {
            $router.back();
          }
        } "
    />
  
    <div id="local-player" class="player">
      <img src="https://i.postimg.cc/2yc7SW-6W/banner1.jpg"
           v-if="!living" alt="" style="height: 520px;width: 720px;"/>
    </div>
    <div style="margin-left: 66%;" v-if="!living">
      <a-button :disabled="living" size="large"
                @click="joinOps" shape="round"
                type="primary">
        开启课堂
      </a-button>
    </div>
    <br/>
    <div style="margin-left: 66%;" v-if="!!living">
      <a-button size="large" @click="backHandler" shape="round" type="primary">
        结束课堂
      </a-button>
    </div>
  </template>
  
  <script lang="ts">
  import {createVNode, defineComponent, ref, onMounted} from "vue";
  import {useRoute, useRouter} from "vue-router";
  import axios from 'axios';
  import {message, Modal} from 'ant-design-vue'
  import {ExclamationCircleOutlined} from '@ant-design/icons-vue';
  
  
  interface userIn {
    videoTrack: any,
    audioTrack: any
    uid: any,
  }
  
  declare let AgoraRTC: any;
  export default defineComponent({
    name: 'AdminLive',
    components: {},
    setup() {
  
      const living = ref(false);
  
      // 路由对象 用于获取queryId
      const route = useRoute();
  
      const router = useRouter();
  
      const client = AgoraRTC.createClient({
        codec: "vp8",
        mode: "rtc",
      });
      AgoraRTC.enableLogUpload();
  
      const localTracks: any = {
        screenVideoTrack: null,
        audioTrack: null,
        screenAudioTrack: null
      };
  
      const options: any = {
        // appid从声网控制台获取
        appid: 'xxxx',
        token: '',
        channel: '',
        uid: 0,
        role: ''
      };
  
      // 从服务器获取 Token
      const fetchToken = () => {
        return new Promise(function (resolve) {
          axios.post('/api/admin/live/token/apply', {
            appId: options.appid,
            uid: options.uid,
            channel: options.channel,
            publish: options === 'host'
          }).then(function (response) {
            const data = response.data;
            if (data.success) {
              resolve(data.content.token);
            }
  
          }).catch(function (error) {
            console.log(error);
          });
        })
      }
  
      // 视频流join操作
      const joinOps = async () => {
        try {
          await join();
        } catch (error) {
          console.error(error);
        }
      }
  
      // 开启直播推流
      const join = async () => {
        let screenTrack = [];
        message.info("正在获取直播凭证...");
        // 将获取到的 Token 赋值给 join 方法中的 token 参数
        options.token = await fetchToken();
        // join a channel and create local tracks, we can use Promise.all to run them concurrently
        message.info("正在建立连接...");
        await client.join(options.appid, options.channel, options.token, options.uid);
        // ** create local tracks, using microphone and screen
        localTracks.audioTrack = await AgoraRTC.createMicrophoneAudioTrack();
        message.info("正在获取设备权限...");
        screenTrack = await AgoraRTC.createScreenVideoTrack({
          encoderConfig: {
            framerate: 15,
            height: 720,
            width: 1280
          }
        }, "enable");
        if (screenTrack instanceof Array) {
          localTracks.screenVideoTrack = screenTrack[0]
          localTracks.screenAudioTrack = screenTrack[1]
        } else {
          localTracks.screenVideoTrack = screenTrack
        }
        // play local video track
        localTracks.screenVideoTrack.play("local-player");
        localTracks.screenVideoTrack.on("track-ended", () => {
          localTracks.screenVideoTrack && localTracks.screenVideoTrack.close()
          localTracks.screenAudioTrack && localTracks.screenAudioTrack.close();
          localTracks.audioTrack && localTracks.audioTrack.close();
        });
        // publish local tracks to channel
        if (localTracks.screenAudioTrack == null) {
          await client.publish([localTracks.screenVideoTrack, localTracks.audioTrack]);
        } else {
          await client.publish([localTracks.screenVideoTrack, localTracks.audioTrack, localTracks.screenAudioTrack]);
        }
        message.success("连接成功");
        living.value = true;
        // 收到 token-privilege-will-expire 回调时，从服务器重新申请一个 Token，并调用 renewToken 将新的 Token 传给 SDK
        client.on("token-privilege-will-expire", async function () {
          let token = await fetchToken();
          await client.renewToken(token);
        });
  
        // 收到 token-privilege-did-expire 回调时，从服务器重新申请一个 Token，并调用 join 重新加入频道
        client.on("token-privilege-did-expire", async function () {
          console.log("Fetching the new Token")
          options.token = await fetchToken();
          console.log("Rejoining the channel with new Token")
          await client.join();
        });
        console.log("publish success");
      }
  
      // 离开直播 停止推流
      const leave = async () => {
        Object.keys(localTracks).forEach((trackName: any) => {
          let track = localTracks[trackName];
          if (track) {
            track.stop();
            track.close();
            localTracks[trackName] = undefined;
          }
        })
        // leave the channel
        await client.leave();
        console.log("client leaves channel success");
        setTimeout(() => {
          router.back();
        }, 1000);
      }
  
      // 课程信息
      const course = ref();
      // 直播课时ID
      const contentId = ref();
  
      // 下播的操作
      const leaveOps = async () => {
        await leave();
        axios.post("/api/admin/live/finish", {
          courseId: route.query.courseId,
          contentId: contentId.value
        }).then((res) => {
          const data = res.data;
          if (data.success) {
            message.success(data.message);
            living.value = false;
          } else {
            message.error(data.message);
          }
        })
      };
  
      // 下播确认
      const backHandler = () => {
        Modal.confirm({
          title: '是否结束课堂直播？',
          icon: createVNode(ExclamationCircleOutlined),
          okText: '确定',
          cancelText: '取消',
          onOk() {
            leaveOps();
          }
        })
      }
  
      // 查询课程信息
      const queryCourse = (courseId: any) => {
        axios.get("/api/common/course/content", courseId).then((res) => {
          const data = res.data;
          if (data.success) {
            course.value = data.content;
          }
        })
      }
  
      onMounted(() => {
        queryCourse(route.query.courseId);
        contentId.value = route.query.contentId;
        options.channel = route.query.channel;
        options.token = route.query.token;
        options.role = route.query.role;
        console.log(options)
        if (route.query.channel === null && route.query.token === null && route.query.role === null) {
          router.back();
        }
      })
  
      return {
        joinOps,
        leaveOps,
        backHandler,
        living,
        course
      }
    }
  })
  </script>
  <style>
  
  .player {
    width: 47%;
    height: 80%;
    margin-left: 25%;
  }
  
  @media (max-width: 1920px) {
    .player {
      width: 47%;
      height: 80%;
      margin-left: 25%;
    }
  }
  
  </style>
  